<script setup lang="ts">

import { loginByPassword } from '@/api/user';
import { md5 } from 'js-md5';
import { computed, nextTick, ref, type Ref } from 'vue'
import { useToast } from '@/composables/useToast'
import { useRoute, useRouter } from 'vue-router';
import { saveUser } from '@/utils/auth';

type SelectMode = 'sms' | 'password';
const sel = ref<SelectMode>('password')
const smsCode = ref('')
const password = ref('')
const is_look = ref<boolean>(false)
const account = ref('')
const phone = ref('')
const placeholder = computed(() => sel.value === 'password' ? '请输入密码' : '验证码')
const account_placeholder = computed(() => sel.value === 'password' ? '请输入用户名' : '请输入手机号')
const maxlength = computed(() => sel.value === 'password' ? undefined : 6)
const inputmode = computed(() => sel.value === 'password' ? undefined : 'numeric')
const inputType = computed(() => is_look.value === false ? 'password' : 'text')
const autocompleteAttr = computed(() => sel.value === 'password' ? 'current-password' : 'one-time-code')
const accountInputRef = ref<HTMLInputElement | null>(null)
const passwordInputRef = ref<HTMLInputElement | null>(null)
const accountErr = ref(false) 
const passwordErr = ref(false)
const agree = ref(false)
const router = useRouter();
const route = useRoute();

/**
 * 让输入框获得焦点，并让外层显示短暂的错误高亮
 * @param errRef   控制错误样式的布尔 ref（例如 accountErr）
 * @param inputRef 需要聚焦的 <input> 的 ref
 * @param duration 错误样式持续时间(ms)，默认 1200
 */
function flashInput(
  errRef: Ref<boolean>,
  inputRef: Ref<HTMLInputElement | null>,
  duration = 1200
) {
  // 打开错误样式
  errRef.value = true

  // 聚焦并滚动到视口
  nextTick(() => {
    inputRef.value?.focus()
    inputRef.value?.scrollIntoView?.({ block: 'center', behavior: 'smooth' })
  })

  // 一段时间后恢复
  window.setTimeout(() => (errRef.value = false), duration)
}

const currentSelected = computed({
  get() { return sel.value === 'password' ? password.value : smsCode.value },
  set(v: string) { sel.value === 'password' ? (password.value = v) : (smsCode.value = v) }
})

const currentUser =  computed({
  get() { return sel.value === 'password' ? account.value : phone.value },
  set(v: string) { sel.value === 'password' ? (account.value = v) : (phone.value = v) }
})

/** 只在 sms 模式限制为数字，并可限制长度 */
function onUserInput(e: Event) {
  const el = e.target as HTMLInputElement
  if (sel.value === 'sms') {
    const digits = el.value.replace(/\D+/g, '').slice(0, 11) // 只保留数字，最多11位
    if (digits !== el.value) el.value = digits               // 同步光标/显示
    currentUser.value = digits
  } else {
    currentUser.value = el.value
  }
}

/** 键盘级拦截（回退、方向键等要放行） */
function onKeydown(e: KeyboardEvent) {
  if (sel.value !== 'sms') return
  const allow = [
    'Backspace','Delete','ArrowLeft','ArrowRight','Home','End','Tab'
  ]
  if (allow.includes(e.key) || (e.ctrlKey || e.metaKey)) return
  if (!/^\d$/.test(e.key)) e.preventDefault()
}

async function onLogin() {
    if (sel.value === 'password')
    {
        if (!account.value.trim()) {
            useToast().info('用户名不能为空!!!');
            flashInput(accountErr, accountInputRef);
            return;
        }

        if (!password.value.trim()) {
            useToast().info('密码不能为空!!!');
            flashInput(passwordErr, passwordInputRef);
            return;
        }

        if (agree.value === false) {
            useToast().info('请阅读隐私保护并勾选!!!');
            return;
        }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
        try {
            const res = await loginByPassword({account: account.value, password: md5(password.value)});
            if (res.code === 200) {
               // 1) 保存用户信息（包含 token）
                saveUser(res.data);

                // 2) 跳转：优先按 redirect 回原页面，否则去 Home
                const redirect = (router.currentRoute.value.query.redirect as string) || { name: 'Home' };
                router.replace(redirect);
            }
            else {
                useToast().error(res.msg);
            }
        } catch (e:any) {
            console.error(e.message);
        }
    }
    else 
    {
        useToast().warning('当前还未实现手机号码+验证码登录!!!');
    }
}

</script>

<template>
	<main class="login-wrap">
		<div class="icon-box">
			<!-- <div>
				<p class="title neon">毛孩子成长日记</p>
			</div>
			<div>
				<img class="logo" src="@/assets/images/login/mc_icon.png"></img>
			</div> -->
		</div>
		<div class="login-box">
			<div class="login-card">
				<div class="title-box">
					<h2 class="card-title">欢迎使用-毛孩子成长日记</h2>
				</div>
                <div class="seg">
                    <button 
                        class="seg-btn"
                        :class="{active: sel ==='password'}"
                        @click="sel = 'password', is_look = false,  smsCode = ''">账号登录
                    </button>
                    <button 
                        class="seg-btn"
                        @click="sel = 'sms', is_look = true, password=''"
                        :class="{active: sel ==='sms'}">短信登录
                    </button>
                </div>
				<div class="box">
                    <div class="input-field" :class="{ 'has-error': accountErr }">
                        <input
                            ref="accountInputRef"
                            v-model="currentUser"
                            :placeholder="account_placeholder"
                            :inputmode="sel === 'sms' ? 'numeric' : undefined"
                            :maxlength="sel === 'sms' ? 11 : undefined"
                            @input="onUserInput"
                            @keydown="onKeydown"/>
                    </div>
					<div class="input-field" :class="{ 'has-error': passwordErr }">
                        <input
                            ref="passwordInputRef"
                            v-model="currentSelected"
                            :placeholder="placeholder"
                            :inputmode="inputmode"
                            :maxlength="maxlength"
                            :type="inputType"
                            :autocomplete="autocompleteAttr"
                            />
                        <button class="send" v-if="sel === 'sms'">
                        发送
                        </button>
                        <button 
                            class="look-over" 
                            @click="is_look = !is_look"
                            v-else>
                            <svg v-if="is_look === false" t="1762501267975" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2596" width="24" height="24"><path d="M847.76000031 391.59999969a26.68000031 26.68000031 0 0 0-4.88000063-34.39999969c-10.92-8.64-25.51999969-6.16000031-33.99999937 4.92-1.24000031 1.2-136.24000031 162.40000031-296.80000031 162.40000031-155.59999969 0-296.68000031-162.40000031-297.91999969-163.60000031a24.48 24.48 0 0 0-34.00000031-2.4 25.2 25.2 0 0 0-2.47999969 34.39999969c2.44000031 3.72 31.60000031 36.91999969 77.83999969 73.84000031l-61.96000032 65.20000031a24 24 0 0 0 1.2 34.44c2.47999969 4.96000031 8.56000031 7.39999969 14.64 7.39999969a23.88 23.88 0 0 0 17.00000063-7.39999969l66.87999937-70.12000031A472.00000031 472.00000031 0 0 0 404.00000031 554.12l-25.52000063 87.12a24.64000031 24.64000031 0 0 0 17.00000063 30.76000031h7.32a23.47999969 23.47999969 0 0 0 23.07999937-18.44000062l25.56-87.36a328.75999969 328.75999969 0 0 0 60.80000063 6.16000031c20.68000031 0 41.35999969-2.47999969 60.79999969-6.16000031l25.51999968 86.12000062c2.44000031 11.08000031 13.39999969 18.43999969 23.12000063 18.43999969 2.4 0 4.87999969 0 6.07999969-1.2a24.64000031 24.64000031 0 0 0 17.04-30.79999969l-25.60000032-85.96000031a472.00000031 472.00000031 0 0 0 110.64-57.79999969l65.68000032 68.88a23.88 23.88 0 0 0 16.99999968 7.39999969 23.88 23.88 0 0 0 17.04-7.39999969 25.15999969 25.15999969 0 0 0 1.2-34.44l-61.99999968-65.20000031c49.92-36.91999969 79.03999969-72.6 79.03999968-72.6z" fill="#cdcdcd" p-id="2597"></path></svg>
                            <!-- <svg v-if="is_look === false" t="1762501217136" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2864" width="24" height="24"><path d="M969.34763205 345.74676447a36.84083359 36.84083359 0 0 0-6.73850409-47.50092388c-15.07878178-11.93046471-35.23905738-8.5059799-46.94858711 6.79373685-1.71224305 1.65700898-188.12575417 224.24855009-409.83355671 224.24855009-214.85883164 0-409.66785582-224.24855009-411.38009757-225.90555908a33.80298335 33.80298335 0 0 0-46.94858842-3.31401796 34.79718875 34.79718875 0 0 0-3.42448481 47.50092388c3.36925203 5.13672786 43.63457043 50.98064276 107.48464924 101.96128679l-85.55689784 90.0308221a33.14017975 33.14017975 0 0 0 1.65700901 47.55615795c3.42448481 6.84897091 11.81999788 10.21822166 20.21550963 10.21822165a32.97447885 32.97447885 0 0 0 23.47429487-10.21822165l92.35063336-96.82455895A651.75686892 651.75686892 0 0 0 356.58570841 570.16101547l-35.23905866 120.2988525a34.0239183 34.0239183 0 0 0 23.47429484 42.47466415h10.10775483a32.4221421 32.4221421 0 0 0 31.86980534-25.46270565l35.29429144-120.63025429a453.96522855 453.96522855 0 0 0 83.9551229 8.50597991c28.55578865 0 57.11157601-3.42448481 83.95512161-8.50597991l35.23905737 118.91801255c3.36925203 15.29971675 18.5032666 25.46270434 31.9250407 25.46270434 3.31401797 0 6.73850278 0 8.39551177-1.65700898a34.0239183 34.0239183 0 0 0 23.52952761-42.52989693l-35.34952548-118.69707758a651.75686892 651.75686892 0 0 0 152.77622865-79.81259915l90.69362569 95.11231591a32.97447885 32.97447885 0 0 0 23.47429356 10.21822166 32.97447885 32.97447885 0 0 0 23.52952762-10.21822166 34.74195468 34.74195468 0 0 0 1.65700899-47.55615796l-85.6121306-90.03082209c68.93157389-50.98064276 109.14165823-100.24904375 109.14165823-100.24904375z" fill="#cdcdcd" p-id="2865"></path></svg> -->
                            <svg v-else t="1762501173502" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2566" width="24" height="24"><path d="M512.45511111 217.088C243.25688889 217.088 40.96 415.28888889 40.96 513.25155555c0 97.96266667 201.50044445 296.50488889 471.38133333 296.5048889 277.04888889 0 471.38133333-201.84177778 471.38133334-296.5048889 0.11377778-97.96266667-192.17066667-296.16355555-471.26755556-296.16355555z m0.34133334 538.51022222c-125.49688889 0-227.21422222-108.43022222-227.21422223-242.23288889 0-133.80266667 101.71733333-242.23288889 227.21422223-242.23288888 125.49688889 0 227.21422222 108.43022222 227.21422222 242.23288888 0 133.80266667-101.71733333 242.23288889-227.21422222 242.23288889z m-0.34133334-396.85688889c-79.872 0-144.72533333 69.06311111-144.72533333 154.28266667s64.73955555 154.28266667 144.72533333 154.28266667c79.872 0 144.61155555-69.06311111 144.61155556-154.28266667s-64.73955555-154.28266667-144.61155556-154.28266667z" fill="#cdcdcd" p-id="2567"></path></svg>
                        </button>
                    </div>
                    <div>
                        <button class="login-btn" @click="onLogin">登 录</button>
                    </div>
				</div>
                <div style="display: flex; flex-direction: row; width: 100%; justify-content: space-between">
                    <div>
                        <input v-model="agree" type="checkbox" id="agree" style="transform: scale(1.2); transform-origin: center;"></input>
                        <label for="agree" style="cursor:pointer; padding-left: 4px; align-self: center;">阅读并同意</label>
                        <a style="color: #336FFF;" href="/privacy.html" target="_blank" rel="noopener">《隐私政策》</a>
                    </div>
                    <div>
                        <button class="forget-password" v-if="sel === 'password'">忘记密码</button>
                    </div>
                </div>
                <div class="register" style="display: flex; flex-direction: row; justify-content: center;">
                    <span>还没有账号?</span> <a style="color: #336FFF; padding-left: 10px;" href="">注册</a>
                </div>
			</div>
		</div>
	</main>
</template>

<style scoped>

/* 背景 */
.login-wrap{
  min-height: 100dvh;
  min-width: 100dvw;
  display: flex;
  flex-direction: row;
  background-image: url('@/assets/images/login/background.png');
  background-size: contain;
  background-repeat: no-repeat;
}

.icon-box {
	width: 50%;
	margin-top: 3%;
	/* background-color: antiquewhite; */
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.logo {
	user-select: none; -webkit-user-drag: none; -webkit-touch-callout: none;
}

.title {
	margin: 0;
	font-weight: 900;
	letter-spacing: .08em;
	line-height: 1.1;
	font-size: clamp(32px, 4vw, 64px);
}

.title.neon{
  color: #a7ffd1;                         /* 基底色 */
  text-shadow:
    0 1px 0 #0c2015,                      /* 细描边让字更锐利 */
    0 0 16px rgba(34,197,94,.55),         /* 外发光 */
    0 0 40px rgba(34,197,94,.35);         /* 远发光 */
}

.login-box {
	width: 50%;
	/* background-color: aqua; */
	display: flex;
	align-items: center;
	justify-content: center;
}

.login-card {
	width: 400px;
	height: 460px;
	background-color: rgba(255,255,255,0.85);
	border-radius: 18px;
    padding-left: 6%;
    padding-right: 6%;
    padding-top: 6%;
    padding-bottom: 15px;
	box-shadow:
		0 18px 48px rgba(0,0,0,.45),
		0 2px 8px rgba(0,0,0,.28),
		inset 0 1px 0 rgba(255,255,255,.16);
	backdrop-filter: blur(6px);
	display: flex;
	flex-direction: column; 
	justify-content: start;
	align-items: stretch; 
	gap: 12px; 
	overflow: auto;
}

/* 输入框 */
.field{ 
	position: relative; 
	display: flex; 
	align-items: center;  
}

.field input{
  width: 100%; 
  height: 100%;
  box-sizing: border-box; 
  padding: 10px 12px 10px 38px;
  border: 1px solid #d6dfeb; 
  border-radius: 10px; 
  background: #fff; 
  outline: none;
  transition: .15s border, .15s box-shadow; 
  font-size: 14px;
}

.field input:focus{ border-color: #5b8eff; box-shadow: 0 0 0 3px rgba(91,142,255,.15); }

.title-box {
	display: flex;
	flex-direction: row;
    margin-bottom: 20px;
}

.box {
	display: flex;
	flex-direction: column;
	justify-content: start;
	align-items: stretch; 
	gap: 20px;
}

.card-title{ 
    margin: 0; 
    text-align: start; 
    font-size: 20px; 
    letter-spacing: .1em; 
    color: #1a1a1a; 
}

.select-login {
    width: 65%;
    display: flex;
    flex-direction: row;
    gap: 10px;
}

/* 容器：浅灰背景 + 圆角 + 细边框 */
.input-field{
  display:flex; align-items:center;
  height:42px; 
  padding-left:8px;
  padding-right: 4px;
  background:#f7f8fa;
  border:1px solid #d8e0ff;     /* 常态淡蓝边 */
  border-radius:10px;
  transition:.15s ease;
}

/* 聚焦时高亮描边 */
.input-field:focus-within{
  background:#fff;
  border-color:#2f67ff;
  box-shadow:0 0 0 1px rgba(47,103,255,.18);
}

.input-field input{
  flex:1; height:100%;
  border:0; 
  outline:0; 
  background:transparent;
  font-size:14px; 
  color:#1f2a37;
  font-size: 16px;
}

.input-field.has-error {
  border-color: #ef4444 !important;
  box-shadow: 0 0 0 1px rgba(239, 68, 68, .25) !important;
  animation: shakeX .28s ease-in-out, fadeBorder 1.2s ease-in-out;
}

/* 轻微左右晃动 */
@keyframes shakeX {
  0%,100% { transform: translateX(0) }
  20% { transform: translateX(-4px) }
  40% { transform: translateX(4px) }
  60% { transform: translateX(-3px) }
  80% { transform: translateX(3px) }
}

/* 边框从红 -> 恢复（配合 setTimeout 移除类名） */
@keyframes fadeBorder {
  0%   { border-color: #ef4444 }
  100% { border-color: #d8e0ff } /* 这里改成你正常状态的边色 */
}

/* 右侧发送：文字按钮 + 左侧细分隔线 */
.send{
  height:100%;
  border:0; 
  background: transparent;
  color:#2f67ff; 
  font-size: 16px;
  font-weight: 500; 
  cursor:pointer;
  /* border-left:1px solid #e6e8ee; */
}

/* 外层浅灰圆角底板（可选） */
.seg{
  display:flex; 
  flex-direction: row;
  align-self: start;
  align-items: center;
  justify-content: center;
  gap:10px;
  padding:2px; 
  border-radius:3px;
  background:#f3f4f6;            /* 浅灰底 */
}

/* 按钮基础样式 */
.seg-btn{
  border:0; 
  cursor:pointer;
  padding:4px 8px;
  border-radius:3px;
  background:transparent;
  color:#6b7280;                  /* 灰字 */
  font-weight:500;
  transition:.15s ease;
}

/* 选中态：白底 + 阴影 */
.seg-btn.active{
  background:#fff;
  color:#111827;                  /* 深色文字 */
  box-shadow:
    0 6px 14px rgba(0,0,0,.10),
    inset 0 1px 0 rgba(255,255,255,.6);
}

/* 可选：悬停轻微提升 */
.seg-btn:hover{ filter:brightness(1.02); }

.login-btn {
    width: 100%;
    height:42px; 
    border: none; 
    cursor:pointer;
    padding: 10px 8px;
    border-radius: 8px;
    background-color: #226fff;
    color: white;
    font-weight:700;
    font-size: 16px;
}

.login-btn:hover {
    background-color: #4381FF;
}

.login-btn:active {
    border: none;
    background-color: #336FFF;
}

.look-over {
    border: 0;
    background: transparent;
    align-self: center;
}

.forget-password {
    border: none;
    background: transparent;
    color: #696969;
    font-size: 16px;
}

.forget-password:hover {
    color: #202020;
}

.register {
    margin-top: auto;               /* 关键：把它顶到卡片底部 */
}

</style>